<?php

/*
 * This file is part of the symfony package.
 * (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

require_once(dirname(__FILE__) . '/../lib/BasesfGuardAuthActions.class.php');

/**
 *
 * @package    symfony
 * @subpackage plugin
 * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
 * @version    SVN: $Id: actions.class.php 9999 2008-06-29 21:24:44Z fabien $
 */
class sfGuardAuthActions extends BasesfGuardAuthActions {

    public function executeSignin($request) {
        $user = $this->getUser();
        if ($user->isAuthenticated()) {
            return $this->redirect('@homepage');
        }

        $class = sfConfig::get('app_sf_guard_plugin_signin_form', 'sfGuardFormSignin');
        $this->form = new $class();

        if ($request->isMethod('post')) {
            $this->form->bind($request->getParameter('signin'));
            if ($this->form->isValid()) {
                $values = $this->form->getValues();

                $c = new Criteria();
                $c->add(sfGuardUserPeer::LAST_LOGIN, null, Criteria::NOT_EQUAL);
                $ingresoAnterior = sfGuardUserPeer::doSelect($c);

                if (!empty($ingresoAnterior)) {
                    $this->getUser()->signin($values['user'], array_key_exists('remember', $values) ? $values['remember'] : false);

                    //Primer login en el dia, agregar operacion de caja inicial
                    $primerIngresoDia = sfGuardUserPeer::esPrimerIngresoDia();

                    $con = Propel::getConnection();

                    try {
                        //abrimos la transacción
                        $con->beginTransaction();

                        //operaciones pertinentes contra la base de datos (== 1)
                        if ($primerIngresoDia) {
                            $monto = sfConfig::get('app_caja_valor_inicial_diario');
                            $operacionIngreso = sfConfig::get('app_caja_operacion_ingreso');
                            $motivo = sfConfig::get('app_caja_motivo_inicial_diario');
                            $usuario = $this->getUser()->getGuardUser()->getId();

                            //Nueva Operacion
                            $operacion = OperacionesPeer::agregarOperacion($monto, $motivo, $operacionIngreso, $usuario);

                            //nueva Caja
                            CajaPeer::agregarCaja($monto, $operacion->getOpId());
                            
                        }

                        //si todo va bien guardamos los cambios
                        $con->commit();
                    } catch (Exception $e) {

                        // Hacemos rollback de los cambios en caso de fallo
                        $con->rollback();
                        //devolvemos el error al depurador
                        throw $e;
                    }

                    // always redirect to a URL set in app.yml
                    // or to the referer
                    // or to the homepage
                    $signinUrl = sfConfig::get('app_sf_guard_plugin_success_signin_url', $user->getReferer('@homepage'));

                    return $this->redirect($signinUrl);
                } else {
                    $usernameLogin = $values['user']->getUsername();
                    $firstUser = sfConfig::get('app_first_user');

                    if ($usernameLogin == $firstUser) {
                        $this->getUser()->signin($values['user'], array_key_exists('remember', $values) ? $values['remember'] : false);
                        $signinUrl = sfConfig::get('app_sf_guard_plugin_success_signin_url', $user->getReferer('@homepage'));

                        return $this->redirect($signinUrl);
                    } else {
                        sfContext::getInstance()->getUser()->setFlash('error', 'El usuario admin debe configurar el sistema.');
                    }
                }
            }
        } else {
            if ($request->isXmlHttpRequest()) {
                $this->getResponse()->setHeaderOnly(true);
                $this->getResponse()->setStatusCode(401);

                return sfView::NONE;
            }

            // if we have been forwarded, then the referer is the current URL
            // if not, this is the referer of the current request
            $user->setReferer($this->getContext()->getActionStack()->getSize() > 1 ? $request->getUri() : $request->getReferer());

            $module = sfConfig::get('sf_login_module');
            if ($this->getModuleName() != $module) {
                return $this->redirect($module . '/' . sfConfig::get('sf_login_action'));
            }

            $this->getResponse()->setStatusCode(401);
        }
    }

}
